<?php
class ArticlesController extends AppController {

	var $name = 'Articles';
	var $helpers = array('Time', 'Post');

	function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->deny('add', 'edit');
	}

	function index() {
		$data = false;
		
		$this->paginate = $this->Article->pagianteConditions();
		$data['articles'] = $this->paginate('Article');
		
		if ($data) {
			$data['rhcut'] = 'cut';
			$this->set($data);
#pr($data);
		}
	}


	function add() {
		$id = false;
		if (isset($this->data)) {
			$id = $this->__saveArticle($this->data);
		}
		$this->redirect('/articles/edit' . $id);
	}


	function edit($id=null) {
		$data = false;
		$uid = $this->Auth->user('id');

		if (isset($this->data)) {
			$this->__saveArticle($this->data);
		}

		$c = array('user_id'=>$uid);

		if ($id) {
			$c['Article.id'] = $id;
			$this->data = $this->Article->find('first', array('conditions'=>$c));
//pr($this->data);
			$data['edit'] = 1;
		} else {
			$f = array('id', 'title', 'status_id');
			$o = 'Article.status_id';
			$data['articles'] = $this->Article->find('all', array('conditions'=>$c, 'fields'=>$f, 'order'=>$o));
		}

		if ($data) {
#pr($data);
			$this->set($data);
		}
	}

	function show($id = null) {
		$data = false;
		$id = intval($id);
		if ($id) {
			$c['Article.status_id >'] = 1;
			$c['Article.id'] = $id;
			$data['articles'][] = $this->Article->find('first', array('conditions'=>$c));
		}

		if ($data) {
			$data['rhcut'] = 'full';
			$this->set($data);
		}
	}

	function tags($tag = null) {
		$data = false;
		if ($tag) {
			$this->paginate['conditions'] = 'tags LIKE "%'.$tag.'%" AND Article.status_id > 1 ORDER BY Article.id DESC';
			$data['articles'] = $this->paginate('Article');
		} else {
			$data['articleTags'] = $this->Article->getTags();
		}


		if ($data) {
			$data['rhcut'] = 'cut';
			$this->set($data);
		}

		if (isset($data['articles'])) {
			$this->render('index');
		}
	}


	function __saveArticle($data) {
		$data = $data['Article'];
		App::import('Sanitize');

		$data['user_id'] = $this->Auth->user('id');

		$data['title'] = Sanitize::stripTags($data['title']);

		//$data['body'] = Sanitize::html($data['body']);

		$data['slug'] = preg_replace('/[\s]/', '_', $data['title']);
		//$data['slug'] = Sanitize::paranoid($slug, array('_'));

		if ($id = $this->Article->save($data)) {
			$this->Session->setFlash('saved');
			return $id;
		}
		return false;
	}


}
?>
